package com.song.tree;

import java.util.ArrayList;
import java.util.List;

/**
 *  二叉树的先序、遍历
 *   中序、后序只需要调整调用的顺序
 *    visit(root.getData());
 *    pre(root.leftBinTree);
 *    pre(root.rightBinTree);
 */
public class BinTree {

        private BinTree leftBinTree ;
        private BinTree rightBinTree ;
        private BinTree root ;
        private List<BinTree> list ; //所有节点
        private Object data;

        public BinTree() {

        }

        public BinTree(Object data) {
            this(null , null ,data );
        }
        public BinTree(BinTree left , BinTree right , Object data) {
            this.leftBinTree = left ;
            this.rightBinTree = right ;
            this.data = data ;
        }

        public void createTree(Object[] datas) {
            list = new ArrayList<BinTree>();
            for (Object o : datas ) {
                list.add(new BinTree(o));
            }
            root = list.get(0);
            for (int i = 0 ; i < (datas.length / 2) ; i++) {
                list.get(i).leftBinTree = list.get((i * 2) + 1);
                if (((i * 2) + 2) < list.size()) {
                    list.get(i).rightBinTree = list.get((i*2) + 2);
                }
            }

        }


        public void visit(Object o) {
            System.out.println(o+" ");
        }
        //先序遍历
        public void pre(BinTree root) {
            if (root != null ) {
                visit(root.getData());
                pre(root.leftBinTree);
                pre(root.rightBinTree);
            }
        }

        public static void main(String[] args) {

            BinTree binTree = new BinTree();
            Object[] objects = {1,2,3,7,8,9};
            binTree.createTree(objects);
            binTree.pre(binTree.getRoot());
        }

        public BinTree getLeftBinTree() {
            return leftBinTree;
        }

        public void setLeftBinTree(BinTree leftBinTree) {
            this.leftBinTree = leftBinTree;
        }

        public BinTree getRightBinTree() {
            return rightBinTree;
        }

        public void setRightBinTree(BinTree rightBinTree) {
            this.rightBinTree = rightBinTree;
        }

        public BinTree getRoot() {
            return root;
        }

        public void setRoot(BinTree root) {
            this.root = root;
        }

        public List<BinTree> getList() {
            return list;
        }

        public void setList(List<BinTree> list) {
            this.list = list;
        }

        public Object getData() {
            return data;
        }

        public void setData(Object data) {
            this.data = data;
        }



}
